package com.monolith.jd.demo.common.util;

import com.monolith.jd.demo.common.vo.JdAuthorizationSource;
import com.monolith.jd.demo.common.vo.JdRequestVo;
import com.monolith.jd.demo.common.vo.JdResponseVo;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.Map;

/**
 * 2018/10/1 Create by 郭文梁
 * ApiClient
 * 京东 API 客户端
 *
 * @author 郭文梁
 * @date 2018/10/1
 */
public class JdApiClient {
    /**
     * 时间日期格式
     */
    private static final String DATE_STYLE = "yyyy-MM-dd HH:mm:ss";
    private String apiUrl;
    private String key;
    private String schema;
    private String host;
    private String method;
    private String contentType;
    private String resource;

    public JdApiClient(String apiUrl, String key, String method, String contentType) throws MalformedURLException {
        URL url = new URL(apiUrl);

        this.apiUrl = apiUrl;
        this.key = key;
        this.schema = url.getProtocol();
        this.host = toHostAndPort(url);
        this.method = method;
        this.contentType = contentType;
        this.resource = url.getPath();
    }

    private String toHostAndPort(URL url) {
        String host = url.getHost();
        String schema = url.getProtocol();
        int port = url.getPort();
        if (port <= 0) {
            port = "https".equals(schema) ? 443 : 80;
        }
        return host + ":" + port;
    }

    public JdResponseVo postData(JdRequestVo requestVo, String siteCode, String registerNo, String opCode, Date date) throws IOException {
        final String postBody = requestVo.toJSON();
        JdAuthorizationSource authorizationSource = new JdAuthorizationSource();
        authorizationSource.setKey(key);
        authorizationSource.setSchema(schema);
        authorizationSource.setHost(host);
        authorizationSource.setMethod(method);
        authorizationSource.setResource(resource);
        authorizationSource.setContentType(contentType);
        authorizationSource.setSiteCode(siteCode);
        authorizationSource.setRegisterNo(registerNo);
        authorizationSource.setOpCode(opCode);
        authorizationSource.setDate(DateUtil.format(date, DATE_STYLE));
        authorizationSource.setContent(postBody.getBytes());

        Map<String, String> headers = JdAuthorizationUtil.generateHeaders(authorizationSource);

        String resp = HttpUtil.postWithStringBody(apiUrl, postBody, headers);
        return new JdResponseVo().loadData(resp);
    }
}
